﻿using System;
using System.Collections.Specialized;

namespace GwLib.JqGridMvc.Extensions
{
    public static class ConfigurationManagerExtensions
    {
        public static T GetAndConvert<T>(this NameValueCollection nvc, string key, T defaultValue)
        {
            T data = defaultValue;

            object o = nvc[key];
            if (o == null) data = defaultValue;
            else if (o.GetType() == typeof(T))
            {
                data = (T)o;
            }
            else
            {
                try
                {
                    data = (T)Convert.ChangeType(o, typeof(T));
                }
                catch
                {
                    data = defaultValue;
                }
            }

            return data;
        }
    }
}